﻿using CaptchaGen;
using HPIT.RentHouse.Common;
using HPIT.RentHouse.DTO;
using HPIT.RentHouse.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace HPIT.RentHouse.Admin.Controllers
{
    public class HomeController : Controller
    {
        private readonly IAdminUsersService _adminUsersService;

        public HomeController(IAdminUsersService adminUsersService)
        {
            _adminUsersService = adminUsersService;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetVerCode()
        {
            //1、生成验证码的文字
            string code = CommonHelper.CreateVerifyCode(4);
            //2、临时保存code,登录时需要对比验证
            TempData["VerCode"] = code;
            //3、调用ImageFactory.GenerateImage(验证码文字,宽度,高度,字体大小,扭曲程度(越大越扭曲))
            var img=ImageFactory.GenerateImage(code, 60, 100, 15, 6);
            //4、返回文件File(src, type)
            return File(img, "imgge/jpeg");
        }

        public ActionResult SubmitLogin(LoginDTO loginDTO)
        {
            //1、验证码判断是否为空——如果验证码为空，提示失效
            if (TempData["VerCode"] == null)
            {
                return Json(new AjaxResult(ResultState.Error,"验证码已失效"));
            }
            //2、验证码不为空，判断图形验证码是否正确
            if (TempData["VerCode"].ToString() != loginDTO.VerCode)
            {
                return Json(new AjaxResult(ResultState.Error, "验证码输入有误"));
            }
            //3、调用services的Login方法，结果以Json格式返回
            AjaxResult result= _adminUsersService.Login(loginDTO);
            return Json(result);
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();//登出
            return RedirectToAction("Login");
        }

    }
}